﻿using System;
using System.Threading.Tasks;
using NUnit.Framework;
using SDLib;

namespace SoundDesigner.Samples
{
    public class ConnectionManager
    {
        private Connection _left;
        private Connection _right;
        private IProductManager _productmanager; // needed to create comm adaptors
        private string _programmer;

        public ConnectionManager(IProductManager productmanager, string programmer)
        {
            _productmanager = productmanager;
            _programmer = programmer;
        }

        public Connection GetConnection (CommunicationPort port)
        {
            return port == CommunicationPort.kLeft ? _left : _right;
        }

        public bool StillThere(CommunicationPort port)
        {
            return GetConnection(port).CommAdaptor.CheckDevice(); 
        }

        public async Task Close(CommunicationPort port)
        {
            await GetConnection(port).Close();
        }

        public async Task<bool> ConnectAsync(CommunicationPort port,  IProgress<int> progress = null)
        {
            Connection connection; 
            connection = port == CommunicationPort.kLeft ? _left : _right;
            TestContext.Progress.WriteLine("Connecting");

            if ( connection != null)
            {
                if (connection.IsConnecting)
                {
                    return false;
                }
                await connection.Close();
            }
            else
            {
                Connection nconnection;
                nconnection = new Connection(port, _productmanager, programmer: _programmer,  progress: progress);
                if (port == CommunicationPort.kLeft)
                    _left = nconnection;
                else
                    _right = nconnection;
                connection = nconnection; 
            }
            await connection.Open();
            try
            {
                TestContext.Progress.WriteLine("Getting device information"); 
                await Task.Run(() => connection.GetDeviceInformationBlocking());
                
                if (connection.ConnectedDeviceInfo.ParameterLockState)
                {
                    connection.UnlockParameters();
                }
                TestContext.Progress.WriteLine($"Connected device FW ID: {connection.ConnectedDeviceInfo.FirmwareId} Ver: {connection.ConnectedDeviceInfo.FirmwareVersion}"); 
            } 
            catch
            {
                await connection.Close();
                throw; 
            }
            connection.IsConnected = true; 
            connection.IsConnecting = false;
            return true;
        }
    }
}
